<script setup lang="ts">
import { signInAPI } from '@/apis/signIn'
import { uploadFileAPI } from '@/apis/uploadFile'
import { useUserInfoStore } from '@/store/userInfo'
import type { DriverDetail } from '@/types/api'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const isEdit = ref(false)

const formRef = ref<any>('')

interface SignInFormData extends Record<string, string> {
  name: string
  idNumber: string
  mobile: string
  idCardZPhoto: string
  idCardFPhoto: string
  driverLicensePhoto: string
  taxiCertificate: string
  operationCertificate: string
  personAndCarPhoto: string
  driverPermit: string
  brand: string
  licensePlateNumber: string
}

const formData = ref<SignInFormData>({
  name: '',
  idNumber: '',
  mobile: '',
  idCardZPhoto: '', // 身份证正面
  idCardFPhoto: '', // 身份证反面
  driverLicensePhoto: '',
  taxiCertificate: '',
  operationCertificate: '',
  personAndCarPhoto: '',
  driverPermit: '',
  brand: '',
  licensePlateNumber: '',
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: ['blur', 'change'] },
  ],
  idNumber: [
    { required: true, message: '请输入身份证号码', trigger: ['blur', 'change'] },
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
  ],
  idCardZPhoto: [
    { required: true, message: '请上传身份证照片', trigger: ['blur', 'change'] },
  ],
  idCardFPhoto: [
    { required: true, message: '请上传身份证照片', trigger: ['blur', 'change'] },
  ],
  driverLicensePhoto: [
    { required: true, message: '请上传驾驶证照', trigger: ['blur', 'change'] },
  ],
  taxiCertificate: [
    { required: true, message: '请上传出租车资格证', trigger: ['blur', 'change'] },
  ],
  operationCertificate: [
    { required: true, message: '请上传运营证', trigger: ['blur', 'change'] },
  ],
  personAndCarPhoto: [
    { required: true, message: '请上传人车合照', trigger: ['blur', 'change'] },
  ],
  driverPermit: [
    { required: true, message: '请上传行驶证', trigger: ['blur', 'change'] },
  ],
  brand: [
    { required: true, message: '请输入车辆品牌', trigger: ['blur', 'change'] },
  ],
  licensePlateNumber: [
    { required: true, message: '请输入车牌号', trigger: ['blur', 'change'] },
  ],
}

onLoad((options) => {
  if (!options?.old_data)
    return
  isEdit.value = true
  const oldData = options.old_data as DriverDetail
  formData.value.name = oldData.username
  formData.value.idNumber = oldData.cardid
  formData.value.mobile = oldData.mobile
  formData.value.idCardZPhoto = oldData.card_zimg
  formData.value.idCardFPhoto = oldData.card_fimg
  formData.value.driverLicensePhoto = oldData.zs_img
  formData.value.taxiCertificate = oldData.czczg_img
  formData.value.operationCertificate = oldData.yyz_img
  formData.value.personAndCarPhoto = oldData.rchz_img
  formData.value.driverPermit = oldData.zsz_img
  formData.value.brand = oldData.car_pinpai
  formData.value.licensePlateNumber = oldData.car_num
})

/**
 * @description 处理选择照片事件
 */
function handlePickImage(field: string) {
  uni.chooseFile({
    type: 'image',
    complete: (result) => {
      (result.tempFiles as File[]).forEach(async (file) => {
        const res = await uploadFileAPI({
          tempFilePath: (file as any).path,
          fileType: 'image',
        }, userInfoStore.userInfo!.token!)
        if (res.data) {
          const resData = JSON.parse(res.data)
          formData.value[field] = resData.data.fullurl
        }
      })
    },
  })
}

const handleSubmit = useThrottleFn(() => {
  formRef.value.validate()
    .then(async () => {
      const res = await signInAPI({
        type: isEdit.value ? 'edit' : 'add',
        username: formData.value.name,
        mobile: formData.value.mobile,
        cardid: formData.value.idNumber,
        card_zimg: formData.value.idCardZPhoto,
        card_fimg: formData.value.idCardFPhoto,
        zs_img: formData.value.driverLicensePhoto,
        czczg_img: formData.value.taxiCertificate,
        yyz_img: formData.value.operationCertificate,
        rchz_img: formData.value.personAndCarPhoto,
        zsz_img: formData.value.driverPermit,
        car_pinpai: formData.value.brand,
        car_num: formData.value.licensePlateNumber,
      }, userInfoStore.userInfo!.token)
      if (res.data?.code !== 1)
        return
      uni.showModal({
        title: '提交成功',
        showCancel: false,
        success: () => router.back(),
      })
    })
    .catch((errors: AnyObject[]) => {
      if (errors.length > 0)
        uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)
</script>

<template>
  <uv-form ref="formRef" :model="formData" :rules="rules">
    <uv-form-item prop="name" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
      <ListCell label="姓名">
        <ListInput v-model="formData.name" placeholder="请输入真实姓名" />
      </ListCell>
    </uv-form-item>
    <Divider w="670" />
    <uv-form-item prop="idNumber" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
      <ListCell label="身份证">
        <ListInput v-model="formData.idNumber" placeholder="请输入身份证号" />
      </ListCell>
    </uv-form-item>
    <Divider w="670" />
    <uv-form-item prop="mobile" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
      <ListCell label="手机号">
        <ListInput v-model="formData.mobile" placeholder="请输入手机号" />
      </ListCell>
    </uv-form-item>
    <Divider w="670" />
    <ListCell direction="column">
      <template #header>
        <view class="flex items-center justify-between">
          <view class="text-32rpx text-#333333 leading-45rpx">
            上传身份证照
          </view>
          <view class="text-24rpx text-#BDBDBD leading-32rpx">
            *请保证上传的证件照清晰可见
          </view>
        </view>
      </template>
      <uv-form-item prop="idCardZPhoto" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
        <view class="w-full flex items-center justify-between">
          <PhotoPickerTrigger
            label="拍摄正面"
            :src="formData.idCardZPhoto"
            @tap="handlePickImage('idCardZPhoto')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/id_card_0.png"
              />
            </template>
          </PhotoPickerTrigger>
          <PhotoPickerTrigger
            label="拍摄反面"
            :src="formData.idCardFPhoto"
            @tap="handlePickImage('idCardFPhoto')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/id_card_1.png"
              />
            </template>
          </PhotoPickerTrigger>
        </view>
      </uv-form-item>
      <Spacer h="40" />
      <view class="text-32rpx text-#333333 leading-45rpx">
        上传驾驶证照
      </view>
      <Spacer h="28" />
      <uv-form-item prop="driverLicensePhoto" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
        <view class="w-full flex items-center justify-between">
          <PhotoPickerTrigger
            label="拍摄驾驶证照"
            :src="formData.driverLicensePhoto"
            @tap="handlePickImage('driverLicensePhoto')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/driver_license.png"
              />
            </template>
          </PhotoPickerTrigger>
        </view>
      </uv-form-item>
      <Spacer h="40" />
      <view class="text-32rpx text-#333333 leading-45rpx">
        出租车资格证
      </view>
      <Spacer h="28" />
      <uv-form-item prop="taxiCertificate" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
        <view class="w-full flex items-center justify-between">
          <PhotoPickerTrigger
            label="出租车资格证"
            :src="formData.taxiCertificate"
            @tap="handlePickImage('taxiCertificate')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/driver_license.png"
              />
            </template>
          </PhotoPickerTrigger>
        </view>
      </uv-form-item>
      <Spacer h="40" />
      <view class="text-32rpx text-#333333 leading-45rpx">
        运营证
      </view>
      <Spacer h="28" />
      <uv-form-item prop="operationCertificate" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
        <view class="w-full flex items-center justify-between">
          <PhotoPickerTrigger
            label="拍摄运营证"
            :src="formData.operationCertificate"
            @tap="handlePickImage('operationCertificate')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/driver_license.png"
              />
            </template>
          </PhotoPickerTrigger>
        </view>
      </uv-form-item>
      <Spacer h="40" />
      <view class="text-32rpx text-#333333 leading-45rpx">
        人车合照
      </view>
      <Spacer h="28" />
      <uv-form-item prop="personAndCarPhoto" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
        <view class="w-full flex items-center justify-between">
          <PhotoPickerTrigger
            label="拍摄人车合照"
            :src="formData.personAndCarPhoto"
            @tap="handlePickImage('personAndCarPhoto')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/driver_license.png"
              />
            </template>
          </PhotoPickerTrigger>
        </view>
      </uv-form-item>
      <Spacer h="40" />
      <view class="text-32rpx text-#333333 leading-45rpx">
        行驶证
      </view>
      <Spacer h="28" />
      <uv-form-item prop="driverPermit" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
        <view class="w-full flex items-center justify-between">
          <PhotoPickerTrigger
            label="拍摄行驶证"
            :src="formData.driverPermit"
            @tap="handlePickImage('driverPermit')"
          >
            <template #placeholder>
              <image
                class="h-134rpx w-200rpx"
                src="@/static/images/driver_license.png"
              />
            </template>
          </PhotoPickerTrigger>
        </view>
      </uv-form-item>
    </ListCell>
    <Divider w="670" />
    <uv-form-item prop="brand" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
      <ListCell label="车辆品牌">
        <ListInput v-model="formData.brand" placeholder="请输入车辆品牌" />
      </ListCell>
    </uv-form-item>
    <Divider w="670" />
    <uv-form-item prop="licensePlateNumber" label-position="top" :custom-style="{ padding: 0, margin: 0 }">
      <ListCell label="车牌号">
        <ListInput v-model="formData.licensePlateNumber" placeholder="请输入车牌号" />
      </ListCell>
    </uv-form-item>
    <Divider w="670" />
    <Spacer h="240" />
  </uv-form>
  <view class="fixed bottom-40rpx x-center">
    <RGButton width="670" @tap="handleSubmit">
      提交申请
    </RGButton>
  </view>
</template>

<route lang="yaml">
name: 'signin'
style:
  navigationBarTitleText: '注册司机'
  navigationBarBackgroundColor: 'white'
  navigationBarTextStyle: 'black'
  backgroundColor: 'white'
layout: 'custom'
</route>
